import { isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { addDialog } from "@/components/ReDialog";
import { handleTree, handleTreeNode } from "@/utils/tree";
import { message } from "@/utils/message";
import { getOrgList, createOrg, updateOrg, deleteOrg } from "@/api/sys/org";
import { SysOrg } from "@/api/models/sys_org";
import { useStyleHooks } from "@/views/hooks/style";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";

import editForm from "../form.vue";

export function useOrg() {
  const searchForm = reactive({
    name: "",
    status: null
  });

  const formRef = ref();
  const treeDataList = ref<SysOrg[]>([]);
  const loading = ref(true);
  const { tagStyle } = useStyleHooks();

  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "name",
      width: 260,
      align: "left"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 320
    },
    {
      label: "创建时间",
      prop: "createdTime",
      minWidth: 140,
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function resetForm(formEl: any) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getOrgList(); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id
    let newData = data;
    if (!isAllEmpty(searchForm.name)) {
      // 前端搜索部门名称
      newData = newData.filter(item => item.name.includes(searchForm.name));
    }
    if (!isAllEmpty(searchForm.status)) {
      // 前端搜索状态
      newData = newData.filter(item => item.status === searchForm.status);
    }
    treeDataList.value = handleTree(newData); // 处理成树结构
    loading.value = false;
  }

  function openDialog(mode = "add", row?: FormItemProps) {
    const modeMap: Record<string, string> = {
      add: "新增",
      edit: "编辑"
    };
    addDialog({
      title: `${modeMap[mode]}部门`,
      props: {
        formInline: {
          treeOrgOptions: handleTreeNode(treeDataList.value, item => item.disabled = !item.status),
          id: row?.id ?? 0,
          parentId: row?.parentId ?? 0,
          name: row?.name ?? "",
          code: row?.code ?? "",
          principal: row?.principal ?? "",
          phone: row?.phone ?? "",
          email: row?.email ?? "",
          sort: row?.sort ?? 0,
          status: row?.status ?? 1,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            if (mode === "add") {
              const ret = await createOrg(curData);
              if (!ret.success) {
                message(`新增部门失败，${ret.message}`, { type: "warning" });
                return;
              }
            } else {
              const ret = await updateOrg(curData);
              if (!ret.success) {
                message(`更新部门失败，${ret.message}`, { type: "warning" });
                return;
              }
            }
            chores();
          }
        });
      }
    });
  }

  async function handleDelete(row: any) {
    const ret = await deleteOrg(row.id);
    if (!ret.success) {
      message(`删除部门失败，${ret.message}`, { type: "warning" });
      return;
    }
    onSearch();
  }

  onMounted(() => {
    onSearch();
  });

  return {
    searchForm,
    loading,
    columns,
    treeDataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改部门 */
    openDialog,
    /** 删除部门 */
    handleDelete,
  };
}
